// @algorithm @lc id=1000247 lang=typescript
// @title A1NYOS
function findMaxLength(nums: number[]): number {
  const n = nums.length;
  const map = new Map<number, number>();
  map.set(0, -1);
  let count = 0;
  let ans = 0;
  for (let i = 0; i < n; i++) {
    if (nums[i] === 1) count++;
    else count--;
    if (map.has(count)) {
      ans = Math.max(ans, i - map.get(count));
    } else {
      map.set(count, i);
    }
  }
  return ans;
}
